// src/components/ToolKit/EditableTitle.tsx
import React, { useRef, useEffect } from "react";
import { observer } from "mobx-react-lite";
import { types, Instance } from "mobx-state-tree";
import { Input } from 'antd';
import { DatabaseOutlined } from '@ant-design/icons';

// 定义 EditableTitle 的状态模型
const EditableTitleModel = types.model("EditableTitle", {
  isEditing: types.optional(types.boolean, false),
  value: types.string
}).actions(self => ({
  setEditing(editing: boolean) {
    self.isEditing = editing;
  },
  setValue(value: string) {
    self.value = value;
  },
  save() {
    self.isEditing = false;
  },
  cancel() {
    self.isEditing = false;
  }
}));

interface EditableTitleProps {
  title: string;
  icon?: React.ReactNode;
  onSave: (value: string) => void;
}

const EditableTitle: React.FC<EditableTitleProps> = observer(({ title, icon, onSave }) => {
  // 创建本地状态模型实例
  const titleStore = React.useMemo(() => EditableTitleModel.create({ value: title }), [title]);
  const inputRef = useRef<any>(null);

  // 当 title 属性变化时更新 store 中的值
  React.useEffect(() => {
    titleStore.setValue(title);
  }, [title, titleStore]);

  useEffect(() => {
    if (titleStore.isEditing && inputRef.current) {
      inputRef.current.focus();
    }
  }, [titleStore.isEditing]);

  const handleEdit = () => {
    titleStore.setEditing(true);
    titleStore.setValue(title);
  };

  const handleSave = () => {
    titleStore.save();
    if (titleStore.value.trim() !== title) {
      onSave(titleStore.value);
    }
  };

  const handleCancel = () => {
    titleStore.cancel();
    titleStore.setValue(title);
  };

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') {
      handleSave();
    } else if (e.key === 'Escape') {
      handleCancel();
    }
  };

  return (
    <div onClick={titleStore.isEditing ? undefined : handleEdit} style={{ cursor: titleStore.isEditing ? 'text' : 'pointer' }}>
      {titleStore.isEditing ? (
        <Input
          ref={inputRef}
          value={titleStore.value}
          onChange={(e) => titleStore.setValue(e.target.value)}
          onBlur={handleSave}
          onPressEnter={handleSave}
          onKeyDown={handleKeyDown}
          suffix={icon}
          size="small"
          style={{ width: '100%' }}
        />
      ) : (
        <span style={{ display: 'flex', alignItems: 'center' }}>
          {icon}
          <span style={{ marginLeft: icon ? 8 : 0 }}>{titleStore.value || '点击编辑标题'}</span>
        </span>
      )}
    </div>
  );
});

export default EditableTitle;